package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.pojo.TcCheckinRecord;
import com.zhentao.service.TcCheckinRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("tea/checkinRecord")
public class CheckinRecordController {

    @Autowired
    TcCheckinRecordService checkinRecordService;

    /**
     * 获取全部打卡记录
     */
    @GetMapping("list")
    public List<TcCheckinRecord> list(){
        return checkinRecordService.list();
    }

    /**
     * 根据ID获取打卡记录详情
     */
    @GetMapping("get/{id}")
    public TcCheckinRecord getById(@PathVariable Integer id){
        return checkinRecordService.getById(id);
    }

    /**
     * 添加打卡记录
     */
    @PostMapping("add")
    public Map<String, Object> add(@RequestBody TcCheckinRecord record){
        Map<String, Object> result = new HashMap<>();
        try {
            record.setCheckinTime(new Date());
            boolean success = checkinRecordService.save(record);
            result.put("success", success);
            result.put("message", success ? "打卡成功" : "打卡失败");
            if (success) {
                result.put("data", record);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "打卡失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 更新打卡记录
     */
    @PutMapping("update")
    public Map<String, Object> update(@RequestBody TcCheckinRecord record){
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = checkinRecordService.updateById(record);
            result.put("success", success);
            result.put("message", success ? "更新成功" : "更新失败");
            if (success) {
                result.put("data", record);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 删除打卡记录
     */
    @DeleteMapping("delete/{id}")
    public Map<String, Object> delete(@PathVariable Integer id){
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = checkinRecordService.removeById(id);
            result.put("success", success);
            result.put("message", success ? "删除成功" : "删除失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 根据打卡活动ID获取记录
     */
    @GetMapping("checkinRecords/{checkinId}")
    public List<TcCheckinRecord> getCheckinRecords(@PathVariable Integer checkinId){
        QueryWrapper<TcCheckinRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("checkin_id", checkinId);
        queryWrapper.orderByDesc("checkin_time");
        return checkinRecordService.list(queryWrapper);
    }

    /**
     * 根据用户ID获取打卡记录
     */
    @GetMapping("userRecords/{userId}")
    public List<TcCheckinRecord> getUserRecords(@PathVariable Integer userId){
        QueryWrapper<TcCheckinRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.orderByDesc("checkin_time");
        return checkinRecordService.list(queryWrapper);
    }

    /**
     * 获取用户某个活动的打卡记录
     */
    @GetMapping("userCheckinRecords/{userId}/{checkinId}")
    public List<TcCheckinRecord> getUserCheckinRecords(@PathVariable Integer userId, @PathVariable Integer checkinId){
        QueryWrapper<TcCheckinRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("checkin_id", checkinId);
        queryWrapper.orderByDesc("checkin_time");
        return checkinRecordService.list(queryWrapper);
    }

    /**
     * 获取今日打卡记录
     */
    @GetMapping("todayRecords")
    public List<TcCheckinRecord> getTodayRecords(){
        QueryWrapper<TcCheckinRecord> queryWrapper = new QueryWrapper<>();
        Date today = new Date();
        Date startOfDay = new Date(today.getYear(), today.getMonth(), today.getDate());
        Date endOfDay = new Date(today.getYear(), today.getMonth(), today.getDate() + 1);
        queryWrapper.between("checkin_time", startOfDay, endOfDay);
        queryWrapper.orderByDesc("checkin_time");
        return checkinRecordService.list(queryWrapper);
    }

    /**
     * 获取某日打卡记录
     */
    @GetMapping("dateRecords/{date}")
    public List<TcCheckinRecord> getDateRecords(@PathVariable String date){
        QueryWrapper<TcCheckinRecord> queryWrapper = new QueryWrapper<>();
        // 这里需要根据date参数构造日期范围
        queryWrapper.like("checkin_time", date);
        queryWrapper.orderByDesc("checkin_time");
        return checkinRecordService.list(queryWrapper);
    }

    /**
     * 搜索打卡记录
     */
    @GetMapping("search")
    public List<TcCheckinRecord> searchRecords(@RequestParam String keyword){
        QueryWrapper<TcCheckinRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("content", keyword);
        queryWrapper.orderByDesc("checkin_time");
        return checkinRecordService.list(queryWrapper);
    }

    /**
     * 检查用户今日是否已打卡
     */
    @GetMapping("checkTodayCheckin/{userId}/{checkinId}")
    public Map<String, Object> checkTodayCheckin(@PathVariable Integer userId, @PathVariable Integer checkinId){
        Map<String, Object> result = new HashMap<>();
        try {
            QueryWrapper<TcCheckinRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.eq("checkin_id", checkinId);
            
            Date today = new Date();
            Date startOfDay = new Date(today.getYear(), today.getMonth(), today.getDate());
            Date endOfDay = new Date(today.getYear(), today.getMonth(), today.getDate() + 1);
            queryWrapper.between("checkin_time", startOfDay, endOfDay);
            
            TcCheckinRecord record = checkinRecordService.getOne(queryWrapper);
            result.put("hasCheckedIn", record != null);
            result.put("record", record);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "检查失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取打卡统计信息
     */
    @GetMapping("statistics/{checkinId}")
    public Map<String, Object> getCheckinStatistics(@PathVariable Integer checkinId){
        Map<String, Object> result = new HashMap<>();
        try {
            QueryWrapper<TcCheckinRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("checkin_id", checkinId);
            List<TcCheckinRecord> records = checkinRecordService.list(queryWrapper);
            
            result.put("totalCount", records.size());
            result.put("records", records);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取统计信息失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 批量删除打卡记录
     */
    @DeleteMapping("batchDelete")
    public Map<String, Object> batchDelete(@RequestBody List<Integer> ids){
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = checkinRecordService.removeByIds(ids);
            result.put("success", success);
            result.put("message", success ? "批量删除成功" : "批量删除失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量删除失败：" + e.getMessage());
        }
        return result;
    }
}
